<?php
/**
 * 功能: 登录.
 * User: 文丹
 * Date: 2018/5/16 0016
 * Time: 16:22
 */

namespace app\index\controller;
use app\validate\User;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;
import('API/rongcloud',EXTEND_PATH);
class Login extends Controller{

    /**
     *  登录 （手机号加密码）
     */
    public function enter($phone='',$password=''){
      $check =  (new User())->goCheck();
        if($check){
            return $check;
        }

      $password = md5(trim(input('password')));
      $phone    = trim(input('phone'));
        $check_phone = Db::name('user')->where('phone',$phone)->find();
        if(empty($check_phone)){
            return json(['msg'=>'您还未注册买就省会员,请注册','ok'=>false]);
        }
      $user     = model('User')->findUser($password,$phone);
        if($user){

            $token = settoken();
            $data = [
                'token'=>$token
            ];
            $user_id = $user['id'];

            // 启动事务
            Db::startTrans();
            try{
                $res = model('User')->addToken($data,$user_id);
                $check = Db::name('pid')->where('user_id',$user_id)->find();
                $tis = '';
                $pid = '';
                if(empty($check)){
                    $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                    if($pid){
                        $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$user_id]);
                    }else{
                        $tis = '没有多余的推广位了';
                        $arr = [
                            'phone'=>$phone,
                            'content'=>$tis,
                            'time'=>time(),
                        ];
                        Db::name('warning')->insert($arr);
                    }
                }else{
                    $pid = $check['adzone_pid'];
                }

                // 提交事务
                Db::commit();
                return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>$e->getMessage(),'ok'=>false]);
            }

        }else{
            return json(['msg'=>'用户名或密码错误！','ok'=>false]);
        }

    }


    /**
     * 退出登录
     */
    public function outLogin(){
        // 删除（当前作用域）
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }
        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $token = '';
        $data = [
            'token'=>$token
        ];
        $res = model('User')->saveToken($data,$user_id);
        if($res){
            Session::delete('user_id');
            Session::delete('user_phone');

            return json(['msg'=>'已退出！','ok'=>true]);
        }else{
            return json(['msg'=>'请求失败！','ok'=>false]);
        }

    }

    /**
     * 微信第三方登录
     */
    public function wei(){
        $openid = trim(input('openid'));
        $w_nickname = trim(input('nickname'));
        $w_photo = trim(input('photo'));
        if(empty($openid)||empty($w_nickname)||empty($w_photo)){
            return json(['msg'=>'数据信息不完整！','ok'=>false]);
        }
        $user = Db::name('user')->where('openid',$openid)->find();

        if($user){
            //app账号存在
            $token = settoken();
            $data = [
                'token'=>$token,
            ];
            $user_id = $user['id'];

            // 启动事务
            Db::startTrans();
            try{
                Db::name('user')->where('id',$user_id)->update($data);
                $check = Db::name('pid')->where('user_id',$user_id)->find();
                $tis = '';
                $pid = '';
                if(empty($check)){
                    $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                    if($pid){
                        $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$user_id]);
                    }else{
                        $tis = '没有多余的推广位了';
                    }
                }else{
                    $pid = $check['adzone_pid'];
                }

                // 提交事务
                Db::commit();
                return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>$e->getMessage(),'ok'=>false]);
            }

        }else{

            /**
             * 微信账号不存在
             */
            return json(['msg'=>'未绑定手机号，去用手机号注册，再绑定~！','ok'=>false]);
        }

    }
    /**
     * 微信登录绑定手机号 第一次登录
     */
    public function w_phone(){
        $openid = trim(input('openid'));
        $w_nickname = trim(input('nickname'));
        $w_photo = trim(input('photo'));
        $phone = trim(input('phone'));
        $mark = strtoupper(trim(input('mark')));
        if(empty($openid)||empty($w_nickname)||empty($w_photo)){
            return json(['msg'=>'数据信息不完整！','ok'=>false]);
        }
        $user = Db::name('user')->where('openid',$openid)->find();

        if($user){
            //app账号存在
            $token = settoken();
            $data = [
                'token'=>$token
            ];
            $user_id = $user['id'];

           /* if($res){
                return json(['msg'=>'登录成功！','ok'=>true,'token'=>$token]);
            }else{
                return json(['msg'=>'登录失败，请稍后再试~！','ok'=>false]);
            }*/
            // 启动事务
            Db::startTrans();
            try{
                $res =Db::name('user')->where('id',$user_id)->update($data);
                $check = Db::name('pid')->where('user_id',$user_id)->find();
                $tis = '';
                $pid = '';
                if(empty($check)){
                    $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                    if($pid){
                        $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$user_id]);
                    }else{
                        $tis = '没有多余的推广位了';
                    }
                }else{
                    $pid = $check['adzone_pid'];
                }

                // 提交事务
                Db::commit();
                return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>$e->getMessage(),'ok'=>false]);
            }

        }else{

            /**
             * 微信账号不存在
             */

            $parent = Db::name('user')->where('mark',$mark)->find();
            if($parent){
                $parent_id = $parent['id'];
            }else{
                $res = Db::name('plat')->where('mark',$mark)->find();
                if($res){
                    $parent_id = 0;
                }else{
                    return json(['msg'=>'邀请码错误','ok'=>false]);
                }
            }
            $check = Db::name('user')->where('phone',$phone)->find();
            $token = settoken();
            $data = [
                'token'=>$token,
                'phone'=>$phone,
                'openid'=>$openid,
                'w_nickname'=>$w_nickname,
                'w_photo'=>$w_photo,
                'parent_id'=>$parent_id
            ];
            if($check){

                // 启动事务
                Db::startTrans();
                try{
                    $user =Db::name('user')->where('phone',$phone)->update($data);
                    Db::name('user')->where('mark',$mark)->setInc('member');
                    $superior =  Db::name('user')->where('mark',$mark)->value('parent_id');//上一级
                    if($superior){
                        Db::name('user')->where('id',$superior)->setInc('member');
                    }

                    $check = Db::name('pid')->where('user_id',$check['id'])->find();
                    $tis = '';
                    $pid = '';
                    if(empty($check)){
                        $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                        if($pid){
                            $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$check['id']]);
                        }else{
                            $tis = '没有多余的推广位了';
                        }
                    }else{
                        $pid = $check['adzone_pid'];
                    }


                    // 提交事务
                    Db::commit();
                    return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $error = $e->getMessage();
                    return json(['msg'=>$error,'ok'=>false]);
                }
            }else{

                // 启动事务
                Db::startTrans();
                try{
                    $user_id =Db::name('user')->insertGetId($data);
                    Db::name('user')->where('mark',$mark)->setInc('member');
                    $superior =  Db::name('user')->where('mark',$mark)->value('parent_id');//上一级
                    if($superior){
                        Db::name('user')->where('id',$superior)->setInc('member');
                    }

                    $check = Db::name('pid')->where('user_id',$user_id)->find();
                    $tis = '';
                    $pid = '';
                    if(empty($check)){
                        $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                        if($pid){
                            $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$user_id]);
                        }else{
                            $tis = '没有多余的推广位了';
                        }
                    }else{
                        $pid = $check['adzone_pid'];
                    }

                    // 提交事务
                    Db::commit();
                    return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $error = $e->getMessage();
                    return json(['msg'=>$error,'ok'=>false]);
                }
            }

        }
    }

    /**
     * 短信登录
     */
    public function sms_login(){
        $code = useful_time(35);//验证码有效时间35分钟

        $verify = trim(input('verify'));
        $phone  = trim(input('phone'));
        $s_phone = session('phone');
        if($phone!=$s_phone){
            return json(['msg'=>'发送短信的手机号与提交的手机号不一致','ok'=>false]);
        }
        $check_phone = Db::name('user')->where('phone',$phone)->find();
        if(empty($check_phone)){
            return json(['msg'=>'您还未注册买就省会员,请注册','ok'=>false]);
        }
        if($code){
            if($verify!=$verify){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }
            $user = Db::name('user')->where('phone',$phone)->find();
            if($user){
                $token = settoken();
                $data = [
                    'token'=>$token,
                ];
                $user_id = $user['id'];

               /* if($res){
                    return json(['msg'=>'登录成功','ok'=>true,'token'=>$token]);
                }else{
                    return json(['msg'=>'登录失败，请稍后再试','ok'=>false]);
                }*/
                Db::startTrans();
                try{
                    $res = Db::name('user')->where('id',$user_id)->update($data);
                    $check = Db::name('pid')->where('user_id',$user_id)->find();
                    $tis = '';
                    $pid = '';
                    if(empty($check)){
                        $pid = Db::name('pid')->where('user_id',0)->value('adzone_pid');
                        if($pid){
                            $res = Db::name('pid')->where('adzone_pid',$pid)->update(['user_id'=>$user_id]);
                        }else{
                            $tis = '没有多余的推广位了';
                        }
                    }else{
                        $pid = $check['adzone_pid'];
                    }

                    // 提交事务
                    Db::commit();
                    return json(['msg'=>'登录成功！'.$tis,'ok'=>true,'token'=>$token,'pid'=>$pid]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['msg'=>$e->getMessage(),'ok'=>false]);
                }

            }else{

            }
        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }
    }






}